package com.soft.mainsite.module.content.beetl;

import java.util.List;

import com.soft.mainsite.mybatis.model.TCmsCategory;
import org.beetl.core.Context;
import org.beetl.core.Function;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.soft.mainsite.common.utils.StrUtil;
import com.soft.mainsite.module.category.service.TCmsCategoryService;

/**
 * ServletInitializer
 *
 * @author Jin
 * @create 2017-06-16
 */
@Service
public class ContentSelectCategoryAutomaticFunction implements Function {
    @Autowired
    private TCmsCategoryService categoryService;

    @Override
    public Object call(Object[] objects, Context context) {

        // 站点Id
        Integer siteId = Integer.parseInt(objects[0].toString());
        // 当前栏目Id
        Long currentId = Long.parseLong(objects[1].toString());
        return recursion(currentId, 0L, "", siteId);
    }

    /**
     * 递归输出子节点
     *
     * @param cid
     * @param pid
     * @param tag
     * @param siteId
     * @return
     */
    private String recursion(Long cid, Long pid, String tag, Integer siteId) {
        // 临时拼凑看不懂就放弃
        tag += (StrUtil.isBlank(tag) ? "&nbsp;&nbsp;" : "&nbsp;&nbsp;&nbsp;&nbsp;");
        StringBuffer sbf = new StringBuffer();
        List<TCmsCategory> ctas = categoryService.findCategoryListByPid(pid, siteId);
        if (ctas != null && ctas.size() > 0) {
            String tagMaker = "";
            for (TCmsCategory cat : ctas) {
                if (ctas.lastIndexOf(cat) == (ctas.size() - 1)) {
                    tagMaker = "└";
                } else {
                    tagMaker = "├";
                }

                int childSize = categoryService.findCategoryListByPid(cat.getCategoryId(), siteId).size();
                if ((cat.getAlone() || !StrUtil.isBlank(cat.getUrl())) && childSize == 0) {
                    continue;
                }
                if (childSize > 0) {
                    sbf.append("<optgroup label=\"" + tagMaker + cat.getCategoryName() + "\">");
                    sbf.append(recursion(cid, cat.getCategoryId(), tag, siteId));
                    sbf.append("</optgroup>");
                } else {
                    if (cid.longValue() == cat.getCategoryId().longValue()) {
                        sbf.append("<option value=\"" + cat.getCategoryId() + "\" selected='selected' >" + tag
                                + "&nbsp;" + tagMaker + cat.getCategoryName() + "</option>");
                    } else {
                        sbf.append("<option value=\"" + cat.getCategoryId() + "\" >" + tag + "&nbsp;" + tagMaker
                                + cat.getCategoryName() + "</option>");
                    }
                }
            }
            return sbf.toString();
        }
        return "";
    }
}
